package cn.liwq.demo.biz;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lweiqiang
 * @date 2023/2/3
 */
public class MelamineDownloadBiz {

    public static void download() {
        String url1 =
                "https://exhibitorsearch.messefrankfurt.com/service/esb/2.1/search/exhibitor?"
                        + "language=en-GB&q={}&orderBy=relevance&pageNumber={}&pageSize={}&showJumpLabels=true&findEventVariable=CHRISTMASWORLD";
        String url2 =
                "https://exhibitorsearch.messefrankfurt.com/service/esb/2.1/search/exhibitor?"
                        + "language=en-GB&q={}&orderBy=relevance&pageNumber={}&pageSize={}&showJumpLabels=true&findEventVariable=CREATIVEWORLD";
        String url3 =
                "https://exhibitorsearch.messefrankfurt.com/service/esb/2.1/search/exhibitor?"
                        + "language=en-GB&q={}&orderBy=name&pageNumber={}&pageSize={}&showJumpLabels=true&findEventVariable=AMBIENTE";
        List<String> urls = ListUtil.toList(url1, url2, url3);
        String[] product =
                new String[] {
                    "melamine",
                    "plastic",
                    "disposable",
                    "dinnerware",
                    "serveware",
                    "Decal",
                    "utensil"
                };
        // String[] product = new String[] {"melamine"};
        String fileName = "/Users/liwq/Downloads/厂商列表-" + System.currentTimeMillis() + ".xlsx";
        try (ExcelWriter excelWriter = EasyExcel.write(fileName, CompanyData.class).build()) {
            for (String typeName : product) {
                WriteSheet writeSheet = EasyExcel.writerSheet(typeName).build();
                excelWriter.write(getData(urls, typeName), writeSheet);
            }
        }
    }

    private static List<CompanyData> getData(List<String> urls, String typeName) {
        int pageNum = 1, pageSize = 100;
        JSONArray dataList = new JSONArray();

        for (String url : urls) {
            pageNum = 1;
            while (true) {
                System.out.println(StrUtil.format(url, typeName, pageNum, pageSize));
                String resultStr = HttpUtil.get(StrUtil.format(url, typeName, pageNum, pageSize));
                JSONObject result = JSON.parseObject(resultStr);
                JSONArray hits = result.getJSONObject("result").getJSONArray("hits");
                if (CollUtil.isNotEmpty(hits)) {
                    hits.forEach(
                            hit -> {
                                JSONObject item = ((JSONObject) hit).getJSONObject("exhibitor");
                                JSONObject addr = item.getJSONObject("address");
                                JSONObject country = addr.getJSONObject("country");
                                addr.put("country", country.getString("label"));
                                if (CollUtil.isNotEmpty(item.getJSONArray("contacts"))) {
                                    addr.putAll(item.getJSONArray("contacts").getJSONObject(0));
                                }
                                addr.put("homepage", item.getString("homepage"));
                                if (StrUtil.isBlank(addr.getString("homepage"))
                                        && item.containsKey("exhibition")) {
                                    addr.put(
                                            "homepage",
                                            item.getJSONObject("exhibition").getString("href"));
                                }
                                addr.put("name", HtmlUtil.cleanHtmlTag(item.getString("name")));
                                dataList.add(addr);
                            });
                    pageNum++;
                } else {
                    break;
                }
            }
        }
        return JSON.parseArray(
                dataList.toString(SerializerFeature.PrettyFormat), CompanyData.class);
    }

    public static void main(String[] args) {
        // String path =
        //
        // "/Users/liwq/dev/gitee/springboot-demo/springboot-example/src/main/java/cn/liwq/demo/biz/data.txt";
        // System.out.println(
        //         FileUtil.writeUtf8String(
        //                 JSON.parseObject(FileUtil.readString(path, StandardCharsets.UTF_8))
        //                         .toString(SerializerFeature.PrettyFormat),
        //                 path));
        MelamineDownloadBiz.download();
    }
}
